import React, { useState,useEffect,useRef } from "react";
import {Button, Badge, Dropdown, Col, Card, Layout, Modal, Image, List, message, Row, Select} from "antd";
import {Link, history, FormattedMessage} from '@umijs/max';
import {
    VideoCameraFilled,
    EditFilled,
    VerticalAlignTopOutlined,
    DeleteOutlined,
    EditOutlined,
    EyeOutlined, UpOutlined, DownOutlined
} from '@ant-design/icons';
import {getLoginUserUsingGet} from "@/services/openAPI-backend/userController";
import EditModal  from "@/pages/forumConfig/components/EditModal";
import CreateModal  from "@/pages/forumConfig/components/CreateModal";

import {
    deleteArticleUsingPost, getDraftUsingGet, getPublicUsingGet,
    hotArticleListUsingGet,
    topArticleUsingPost, updateArticleUsingPost
} from "@/services/openAPI-backend/articleController";
import {PageContainer, type ProColumns} from "@ant-design/pro-components";
import {getAllCategoryListUsingGet} from "@/services/openAPI-backend/categoryController";
import {keyframes} from "antd-style";
import {sleep} from "qiankun/es/utils";
const ChatInterface: React.FC = () => {
    const Header = () => {

    }
    const fadeAndScaleIn = keyframes`
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
      `;
    const fadeIn = keyframes`
        from {
            opacity: 0;
            transform: translateY(100%); /* 初始位置在屏幕下方100% */
        }
        to {
            opacity: 1;
            transform: translateY(0); /* 结束位置在正常位置 */
        }
`;
    const [loading, setLoading] = useState(false);
    const [list, setList] = useState<API.PageVo[]>();
    const [total, setTotal] = useState<number>();
    const [categoryList, setCategoryList] = useState<API.CategoryVo[]>([]);
    const [hotArticleList, setHotArticleList] = useState<API.ArticleVo[]>([]);
    const [currentUser, setCurrentUser] = useState<API.UserVo>();
    const [selectedValue, setSelectedValue] = useState();
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [modalData, setModalData] = useState();
    const [createModalOpen, setCreateModalOpen] = useState(false);
    let selectCata = 1;
    const selectRef = useRef(null);
    const handleCreate = () =>{
        setCreateModalOpen(true)
    }
    const getLoginUser = async () => {
        try {
            const res = await getLoginUserUsingGet();
            if (res?.data)
                setCurrentUser(res?.data);
        }catch (e) {
            history.push('/user/login')
        }
    };
    const loadHotArticleList = async () => {
        const res = await hotArticleListUsingGet({
        });
        if (res?.data) {
            setHotArticleList(res?.data);
        }
    }
    const loadCategoryList = async () => {
        const res = await getAllCategoryListUsingGet();
        if (res?.data) {
            setCategoryList(res?.data);
        }
    };
    const onChange = (value: number) => {
        console.log(`selected ${value}`);
        selectCata = value;
        if(value==1)
            setSelectedValue("1")
        if(value==2)
            setSelectedValue("2")
        console.log(selectCata);
        loadData();

    };
    const handleDelete = async (id:number) => {
        try {
            const res = await deleteArticleUsingPost({
                id:id
            })
            if(res.data){
                selectCata = 1;
                setSelectedValue("1")
                message.success("删除成功");
                loadData();
            }else {
                message.error("删除失败");
            }

        }
        catch (e){
            message.error("删除失败");
        }
    };
    const onClose = () => {
        setIsModalOpen(false);
        document.body.style.overflow = 'auto';
        selectCata = 1;
        loadData();
    };
    const onCreateClose = () => {
        setCreateModalOpen(false);
        document.body.style.overflow = 'auto';
        loadData();
    };
    const online = async (item: API.ArticleVo) =>{
        try {
            const res = await updateArticleUsingPost({
                categoryId: item.categoryId,
                content: item.content,
                id: item.id,
                isComment: item.isComment,
                status: 0,
                summary: item.summary,
                thumbnail: item.thumbnail,
                title: item.title,
            })
            if(res.data){
               selectCata = 1;
                 setSelectedValue("1")
                loadData();

                message.success("文章已发布");
            }else {
                message.error("加载失败，请重试'");
            }
        }catch (e) {
            message.error("加载失败，请重试'");
        }
    }
    const offline = async (item: API.ArticleVo) =>{
        try {
            const res = await updateArticleUsingPost({
                categoryId: item.categoryId,
                content: item.content,
                id: item.id,
                isComment: item.isComment,
                status: 1,
                summary: item.summary,
                thumbnail: item.thumbnail,
                title: item.title,
            })
            if(res.data){

                loadData();
                message.success("文章已存入草稿箱");
            }else {
            }
        }catch (e) {
        }
    }


    const showDeleteConfirm = (id:number) => {
        Modal.confirm({
            title: '确认删除',
            content: '是否确认删除该文章？',
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {handleDelete(id)
            },
        });
    };
    const hadleModalOpen = (item) => {
        setModalData(item);
        setIsModalOpen(true);

    };
    const onSearch = (value: string) => {
        console.log('search:', value);
    };
    const loadData = async (pageNum: number = 1, pageSize: number = 10) => {
        setLoading(true);
        if(selectCata == 1) {
            try {
                const res = await getPublicUsingGet({
                    pageNum,
                    pageSize,
                });
                setList(res?.data?.rows ?? []);
                console.log(list);
                setTotal(res.data?.total ?? 0);
            } catch (error) {
                message.error("加载失败，请重试");
            }
            setLoading(false);
        }else if(selectCata == 2) {
            try {
                const res = await getDraftUsingGet({
                    pageNum,
                    pageSize,
                });
                setList(res?.data?.rows ?? []);
                console.log(list);
                setTotal(res.data?.total ?? 0);
            } catch (error) {
                message.error("加载失败，请重试'");
            }
            setLoading(false);
        }
    };
    useEffect(() => {
        loadData();
        loadCategoryList();
        loadHotArticleList();
        getLoginUser();
    }, []);
    useEffect(() => {
        setSelectedValue("1")
    }, [createModalOpen]);
    useEffect(() => {
        setSelectedValue("1")
    }, [isModalOpen]);
    return (
        <PageContainer style={{overflow: 'auto'}} extra={ <div style={{marginRight: '530px'}}><Select
            ref={selectRef}
            showSearch
            placeholder="Select a label"
            optionFilterProp="label"
            value={selectedValue}
            onChange={onChange}
            onSearch={onSearch}
            options={[
                { value: '1', label: '已发布' },
                { value: '2', label: '草稿箱' },
            ]}
        /><Button type={"primary"} ghost={true} style={{marginLeft: '10px'}} onClick={()=>{setCreateModalOpen(true)}}>新增文章</Button></div> }>
            <List  className="Forum-List"
                   loading={loading}
                   itemLayout="vertical"
                   dataSource={list}
                   size="large"
                   style={{marginLeft: '10px', animation: `${fadeAndScaleIn} 2s ease-in-out`}}
                   renderItem={(item, index) => {
                       const apiLink = `/forum/${item.id}`
                       return(
                           <Badge.Ribbon text={<p style={{color: '#ffffff',fontWeight: 'bold',display: 'flex', justifyContent: 'center', alignItems: 'center',marginTop:"3px"}}>{item.categoryName}</p>} style={{marginTop: '100px',height: '30px',width: '80px',animation: `${fadeIn} 1s ease-in-out`}} placement={'start'} color='#1677ff'>
                               <EditModal data={modalData} onCancel={onClose} onSubmit={()=>{console.log("submit")}} isOpen={isModalOpen}/>
                               <CreateModal onCancel={onCreateClose} onSubmit={()=>{console.log("submit")}} isOpen={createModalOpen}/>
                               <Card title={item?.isTop==1?<h3 style={{marginLeft: '30px',marginTop: '10px',fontWeight:"bold"}}>该文章被管理员置顶</h3>:<p></p>}
                                   extra = {<div><Button onClick={()=>{item?.status==1?online(item):offline(item)}} icon={item?.status==1?<UpOutlined />:<DownOutlined />}></Button><Button style={{marginRight: '5px',marginLeft: '5px'}} icon={<DeleteOutlined />} onClick={()=>{showDeleteConfirm(item.id)}} /><Button icon={<EditOutlined />} onClick={()=>{hadleModalOpen(item)}} /></div>} style={{marginBottom: '6px',width: '65%',animation: `${fadeIn} 1s ease-in-out`,borderColor: item?.isTop==1?'#1677ff':'#ffffff'}} hoverable={true} key={index}>
                                   <div
                                       style={{
                                           position: 'absolute', // 使用绝对定位
                                           top: '-15px', // 调整距离顶部的位置
                                           left: '-15px', // 调整距离左侧的位置
                                           backgroundColor: '#1677ff', // 根据需要设置背景颜色
                                           borderRadius: '50%', // 制作圆形
                                           padding: '4px 8px', // 内边距
                                           boxShadow: '0 2px 4px rgba(0,0,0,0.1)', // 可选的阴影效果
                                       }}
                                   >
                                       <div style={{marginTop: "5px",padding:0,marginBottom: '0',color: '#ffffff',display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
                                           {item?.createTime.split("-")[1].split("")[1]}月
                                       </div>
                                       <div style={{display: 'flex', justifyContent: 'center', alignItems: 'center',padding:0,marginTop:-10,marginBottom:'5px'}}>
                                           <p style={{fontSize: '20px',color: '#ffffff',fontWeight: 'bold',marginTop: 0,marginBottom: '0',padding:0,marginLeft: '12px',marginRight: '12px'}}>{item?.createTime.split("-")[2].split(" ")[0]}</p>
                                       </div>
                                   </div>
                                   <div style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
                                       <h2 style={{fontWeight: 'bold'}}>{item?.title}</h2>
                                   </div>
                                   <div style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
                                       <EditFilled/><div style={{marginLeft: '6px',}}>发表于：</div><a style={{
                                       color: 'black',
                                       marginRight: '10px'
                                   }}>{item?.createTime.split(" ")[0]}</a><VideoCameraFilled/><a
                                       style={{marginRight: '6px'}}></a>{item?.viewCount}次观看
                                   </div>
                                   <p style={{marginTop: '15px', marginLeft: '150px'}}>{item?.summary}</p>
                                   <div style={{
                                       display: 'flex',
                                       justifyContent: 'center',
                                       alignItems: 'center',
                                       marginTop: '5px'
                                   }}>
                                       <Image style={{width: '100%'}} preview={false} src={item?.thumbnail}></Image>
                                   </div>
                                   <div style={{
                                       display: 'flex',
                                       justifyContent: 'center',
                                       alignItems: 'center',
                                       marginTop: '10px'
                                   }}>
                                       <Button ghost={true} type={"link"} onClick={()=>{history.push(apiLink)}}>阅读全文</Button>
                                   </div>

                               </Card>
                           </Badge.Ribbon>
                       );
                   }}></List>
            <Card title={<div style={{fontWeight: 'bold'}}> 热门文章</div>} style={{width: '20%',position:"fixed",right:"8%",top:"11.5%",height:'30%',overflow:'auto',maxHeight:'30%',animation: `${fadeAndScaleIn} 1.5s ease-in-out`,}}>
                <List
                    className="Forum-List"
                    loading={loading}
                    itemLayout="vertical"
                    dataSource={hotArticleList}
                    size="small"
                    renderItem={(item, index) => {
                        return (
                            <div style={{marginBottom: '10px'}}><a href={`/forum/${item.id}`} style={{
                                fontWeight: 'bold',
                                fontSize: '17px',
                                color: 'black',
                                marginBottom: '10px'
                            }}>{item.title}<a
                                style={{marginLeft: '10px', color: 'black', fontWeight: 'normal'}}> - {item.viewCount}次观看<br/></a></a>
                            </div>
                        );
                    }
                    }
                ></List>

            </Card>
        </PageContainer>
    );
};

export default ChatInterface;
